﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Twitter;
using System.ComponentModel.Design;
using FriendsNearby.Services;
using FriendsNearby.Services.Facebook;
using InSTEDD.Labs.Geo;

namespace FriendsNearbyBot
{
    internal class FriendsProcessor : IMessageProcessor
    {
        IUsersService userService;
        IPeopleNearbyService peopleService;
        IMessageBuilder messageBuilder;

        public FriendsProcessor(IUsersService userService, IPeopleNearbyService peopleService)
            : this(userService, peopleService, new PlainTextMessageBuilder())
		{
		}

        public FriendsProcessor(IUsersService userService, IPeopleNearbyService peopleService, 
            IMessageBuilder messageBuilder)
        {
            this.userService = userService;
            this.peopleService = peopleService;
            this.messageBuilder = messageBuilder;
        }

        public bool CanProcess(Message message)
        {
            return (message.Text == "friend" || message.Text == "friends" || message.Text == "contact" || message.Text == "contacts");
        }

        public RunNextProcessor Process(IBotClient client, Message message)
        {
            if (CanProcess(message))
            {
				UserRegistry user = userService.QueryUserRegistry(x => x.TwitterScreenName == message.Sender.ScreenName);

                messageBuilder.Clear();
				if (user == null)
                {
                    // Warn the user via SMS that the mapping has not been established.
                    messageBuilder.AppendFragment(String.Format(Properties.Resources.TwitterNotMapped, message.Sender.ScreenName));
                    client.SendMessages(message.Sender.ScreenName, messageBuilder.GetMessages(), message, this.GetType().Name);
                }
                else
                {

					PeopleNearbySummary summary = peopleService.GetPeopleNearbySummary(user.UserID);

                    messageBuilder.AppendFragment(String.Format(Properties.Resources.FriendsResponse, summary.NearbyFriendCount,
                        DistanceHelper.GetDistanceString(summary.NearestDistance)).Pluralize());
                    client.SendMessages(message.Sender.ScreenName, messageBuilder.GetMessages(), message, this.GetType().Name);
                }

                BotProcessor.MessageProcessed(client, message);

                return RunNextProcessor.No;
 
            }
            else
                return RunNextProcessor.Yes;
        }
    }
}
